package cn.rengy.web.framework.shiro.filter.authc;


import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.shiro.web.filter.authc.AuthenticationFilter;
import org.apache.shiro.web.util.WebUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.RequestMethod;

import com.alibaba.fastjson.JSON;

import cn.rengy.lang.ResultEntity;
import cn.rengy.tool.web._WebUtils;

/**
 * 约定登录认证URL不会进入这个Filter,所以并没有判断是否是认证URL
 *  登录认证过滤器 对ajax请求设置响应头在页面进行处理
 *  忽略OPTIONS请求
 * @author rengy
 *
 */
public class IAuthenticationFilter extends AuthenticationFilter {

    private static final Logger LOGGER = LoggerFactory.getLogger(IAuthenticationFilter.class);
    
    public IAuthenticationFilter(){
    	setName("authen");
    }
    @Override
    public boolean onPreHandle(ServletRequest servletRequest, ServletResponse response, Object mappedValue) throws Exception {
    	HttpServletRequest request = (HttpServletRequest) servletRequest;
    	if(request.getMethod().equals(RequestMethod.OPTIONS.name())) {
			return true;
		}
    	return super.onPreHandle( request,  response,  mappedValue);
    }
    /*@Override
    protected boolean isAccessAllowed(ServletRequest servletRequest, ServletResponse response, Object mappedValue) {
    	//HttpServletRequest request = (HttpServletRequest) servletRequest;
    	LOGGER.debug("<header");
    	for (Enumeration<String> eh = request.getHeaderNames(); eh.hasMoreElements();){
			String key = eh.nextElement();
			String value = request.getHeader(key);
			LOGGER.debug("{}={}",key,value);
		}
    	LOGGER.debug("header>");
    	return super.isAccessAllowed(servletRequest, response, mappedValue);
    }*/
    
    
    @Override
    protected boolean onAccessDenied(ServletRequest servletRequest, ServletResponse servletResponse) throws Exception {
    	HttpServletRequest request = (HttpServletRequest) servletRequest;
		HttpServletResponse response = (HttpServletResponse) servletResponse;
		String loginUrl=this.getLoginUrl();
		if(_WebUtils.isAjaxRequest(request)){//ajax请求
			response.setCharacterEncoding(StandardCharsets.UTF_8.name());
			response.setStatus(HttpStatus.UNAUTHORIZED.value());
//			String client=request.getHeader("client");
//			if("uni-app".equals(client)) {
//				//h5模式没有经过cros处理直接响应客户端处理失败 服务器nginx已设置，本地测试需要
//				response.addHeader("Access-Control-Allow-Origin", "*");
//				response.addHeader("Access-Control-Allow-Credentials", "true");
//			}
	        response.setContentType(MediaType.APPLICATION_JSON_VALUE);
	        response.addHeader("Redirect-URL", loginUrl);
	        String str=JSON.toJSONString(ResultEntity.fail("未认证或已失效"));
	        _WebUtils.responseWrite(str, response);
		}else{//链接请求
			Map<String,String> queryParams=new HashMap<String,String>(1);
			queryParams.put("redirect",_WebUtils.getRequestURI(request));
			//loginUrl+="?redirect="+IWebUtils.urlEncode(IWebUtils.getRequestURI(request));
			WebUtils.issueRedirect(request, response, loginUrl,queryParams);
		}
		return false;
    }
}
